var consts = require('../../../util/consts');
const { getUserInfo, addUserOil, addUserConis, saveUserInfo } = require('../../mission/lib/api');
const { getUserByPhone, getUserMoneyAndOil } = require('../../login/lib/dao');
const { dispatch } = require('../../../util/dispatcher');
const { GetCommanderLevel } = require('../lib/signCache');

module.exports = function (app) { return new Handler(app); }
var Handler = function (app) { this.app = app; };
var handler = Handler.prototype;

/**
 * 获取用户基本数据
 * @param msg
 * @param session
 * @param next
 */
handler.c2sGetUserInfo = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');
    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        next(null, {
            code: self.consts.Code.SUC,
            msg: self.consts.Msg.RESULT_SUCCESS,
            data: {
                avatar: userInfo.avatar,
                nickname: userInfo.nickname,
                jewel: userInfo.jewel, //分红宝石
                balance: userInfo.balance,
                profit: userInfo.daily_profit ? userInfo.daily_profit : 0  //今日分红
            }
        });
        return;
    });
}

/**
 * 用户提现申请
 * @param msg
 * @param session
 * @param next
 */
handler.c2sWithdraw = function (msg, session, next) {
    var withdrawJson = this.withdrawJson;
    var cate = msg.cate; //提现类型
    var self = this;
    var uid = session.get('uid');
    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        if (cate == 0) {
            if (userInfo.first_withdraw) {
                next(null, {
                    code: self.consts.Code.ERR,
                    msg: self.consts.Msg.ONLY_ONCE_ERR
                });
                return;
            } else {
                userInfo.first_withdraw = true;
                //将用户信息赋值回login服务器内存
                self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
                });
            }
        }
        if (cate == 6) {
            if (userInfo.second_withdraw) {
                next(null, {
                    code: self.consts.Code.ERR,
                    msg: self.consts.Msg.ONLY_ONCE_ERR
                });
                return;
            } else {
                userInfo.second_withdraw = true;
                //将用户信息赋值回login服务器内存
                self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
                });
            }
        }
        async.waterfall([
            function (callback) {
                widthdrawSync.logQuery(userInfo.uid, 0.3, function (err, count) {
                    callback(err, count)
                })
            }, function (count, callback) {
                if (cate == 0) {
                    if (count > 0) {
                        next(null, {
                            code: self.consts.Code.ERR,
                            msg: self.consts.Msg.ONLY_ONCE_ERR
                        });
                        return;
                    }
                }
                widthdrawSync.logQuery(userInfo.uid, 30, function (err, count) {
                    callback(err, count)
                })
            }, function (count, callback) {
                if (cate == 6) {
                    if (count > 0) {
                        next(null, {
                            code: self.consts.Code.ERR,
                            msg: self.consts.Msg.ONLY_ONCE_ERR
                        });
                        return;
                    }
                }
                widthdrawSync.checkSecondWithdraw(userInfo.uid, 30, function (err, count) {
                    callback(err, count)
                })
            }, function (count, callback) {
                if (cate == 6) {
                    if (count > 0) {
                        next(null, {
                            code: self.consts.Code.ERR,
                            msg: self.consts.Msg.ONLY_ONCE_ERR
                        });
                        return;
                    }
                }
                callback(null)
            }
        ], function (err) {
            if (!!err) {
                next(null, {
                    code: self.consts.Code.ERR,
                    msg: self.consts.Msg.CAN_NOT_WITHDRAW
                });
                return;
            }

            if (utils.typeofData(withdrawJson) == "[object Array]" && withdrawJson.length >= cate) {
                var dataObj = withdrawJson[cate];
                //提现余额不足
                if (userInfo.balance < dataObj.money) {
                    if (cate == 0) {
                        userInfo.first_withdraw = false;
                    } else if (cate == 6) {
                        userInfo.second_withdraw = false;
                    }
                    //将用户信息赋值回login服务器内存
                    self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
                    });
                    next(null, {
                        code: self.consts.Code.ERR,
                        msg: self.consts.Msg.INSUFFICIENT_FUNDS_ERR
                    });
                    return;
                }
                //发送至运营服务器、即时到账
                if (dataObj.money == 0.3) {
                    // 提现券存入redis
                    var ticket = utils.genUuid(utils.consts.TYPE_RAND);
                    async.series([
                        function (callback) {
                            var redis = self.app.get('redis');
                            redis.set(ticket, true, function (err, data) {
                                callback(err);
                            });
                        },
                        function (callback) {
                            var options = {
                                host: self.consts.Configuration.OPERATE_HOST,
                                port: self.consts.Configuration.OPERATE_PORT,
                                path: '/api/money/send?uid=' + userInfo.uid + '&ticket=' + ticket,
                                method: 'GET'
                            };
                            var req = http.request(options, function (res) {
                                res.setEncoding('utf8');
                                res.on('data', function (chunk) {
                                    let jsonObj = JSON.parse('' + chunk);
                                    if (jsonObj.code != '000') {
                                        userInfo.first_withdraw = false;
                                        //将用户信息赋值回login服务器内存
                                        self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
                                        });
                                        callback(jsonObj.message);
                                    } else {
                                        //用户初次提现机会使用完毕
                                        userInfo.balance = parseFloat(userInfo.balance) - 0.3;
                                        if (userInfo.balance < 0) {
                                            userInfo.balance = 0;
                                        }
                                        userInfo.first_withdraw = true;
                                        //将用户信息赋值回login服务器内存
                                        self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
                                        });
                                        //创建提现记录
                                        widthdrawSync.insert(new Widthdraw({
                                            wid: utils.genUuid(utils.consts.TYPE_TIME),
                                            uid: userInfo.uid,
                                            money: dataObj.money,
                                            status: 2,
                                            audit_time: Date.now(),
                                            super_status: 2,
                                            super_audit_time: Date.now(),
                                            gmt_create: Date.now(),
                                            gmt_modified: Date.now()
                                        }), function () {
                                        });
                                        //余额变更消息推送
                                        self.app.rpc.area.areaRemote.pushMessageToClient(session, uid, session.frontendId, consts.PushRoute.BALANCE_REDUCE, {
                                            reduce: dataObj.money,
                                            current: userInfo.balance
                                        }, function (err) {
                                            if (!!err) {
                                                console.log(err)
                                            }
                                        });

                                        callback(null);
                                    }
                                });
                            });
                            req.on('error', function (e) {
                            });
                            req.end();
                        }
                    ], function (err, result) {
                        if (!!err) {
                            userInfo.first_withdraw = false;
                            //将用户信息赋值回login服务器内存
                            self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
                            });
                            next(null, {
                                code: self.consts.Code.ERR,
                                msg: err
                            });
                            return;
                        }
                        next(null, {
                            code: self.consts.Code.SUC,
                            msg: self.consts.Msg.RESULT_SUCCESS
                        });
                        return;
                    });
                } else {
                    //创建提现申请等待审核
                    widthdrawSync.insert(new Widthdraw({
                        wid: utils.genUuid(utils.consts.TYPE_TIME),
                        uid: userInfo.uid,
                        money: dataObj.money,
                        gmt_create: Date.now(),
                        gmt_modified: Date.now()
                    }), function () {
                        //提交审核成功，更新内存中的用户余额
                        userInfo.balance = parseFloat(userInfo.balance) - parseFloat(dataObj.money);
                        if (userInfo.balance < 0) {
                            userInfo.balance = 0;
                        }
                        //将用户信息赋值回login服务器内存
                        self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
                        });
                        //余额变更消息推送
                        self.app.rpc.area.areaRemote.pushMessageToClient(session, uid, session.frontendId, consts.PushRoute.BALANCE_REDUCE, {
                            reduce: dataObj.money,
                            current: userInfo.balance
                        }, function (err) {
                            if (!!err) {
                                console.log(err)
                            }
                            next(null, {
                                code: self.consts.Code.SUC,
                                msg: self.consts.Msg.RESULT_SUCCESS
                            });
                            return;
                        });
                    });
                }
            } else {
                if (cate == 0) {
                    userInfo.first_withdraw = false;
                } else if (cate == 6) {
                    userInfo.second_withdraw = false;
                }
                //将用户信息赋值回login服务器内存
                self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
                });
                next(null, {
                    code: self.consts.Code.ERR,
                    msg: self.consts.Msg.GET_JSON_DATA_ERR
                });
                return;
            }

        });
    });
}

/**
 * 获取用户的提现记录
 * @param msg
 * @param session
 * @param next
 */
handler.c2sWithdrawLog = function (msg, session, next) {
    var uid = session.get("uid");
    var pageNum = msg.page_num ? msg.page_num : 1;
    var pageSize = msg.page_size ? msg.page_size : 100;
    var self = this;
    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!uid) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        //分页查询提现记录
        widthdrawSync.pageQuery({
            uid: uid,
            pageNum: pageNum,
            pageSize: pageSize
        }, function (err, data) {
            if (!!err) {
                next(null, {
                    code: self.consts.Code.ERR,
                    msg: err
                });
                return;
            }
            next(null, {
                code: self.consts.Code.SUC,
                msg: self.consts.Msg.RESULT_SUCCESS,
                data: data
            });
            return;
        });
    });
}

/**
 * 获取邀请用户的分享海报图
 * @param msg
 * @param session
 * @param next
 */
handler.c2sSharePoster = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');
    next(null, {
        code: self.consts.Code.SUC,
        msg: self.consts.Msg.RESULT_SUCCESS,
        data: ""
    });
    return;
    // self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
    //     if (!userInfo) {
    //         next(null, {
    //             code: self.consts.Code.ERR,
    //             msg: self.consts.Msg.USER_NOT_FOUND
    //         });
    //         return;
    //     }
    //
    //     //已经生成过海报图
    //     if (userInfo.poster_list && userInfo.poster_list.poster_three) {
    //         //推送消息给客户端
    //         next(null, {
    //             code: self.consts.Code.SUC,
    //             msg: self.consts.Msg.RESULT_SUCCESS,
    //             data: userInfo.poster_list.poster_three
    //         });
    //         return;
    //     }
    //     var options = {
    //         host: consts.Configuration.OPERATE_HOST,
    //         port: consts.Configuration.OPERATE_PORT,
    //         path: '/api/quick_response_code?uid=' + uid,
    //         method: 'GET'
    //     };
    //     var req = http.request(options, function (res) {
    //         res.setEncoding('utf8');
    //         res.on('data', function (chunk) {
    //             let jsonObj = JSON.parse('' + chunk);
    //             if (jsonObj.code == '000') {
    //                 var postOption = {
    //                     host: consts.Configuration.GRAPH_PATH,
    //                     path: '/graph/compound',
    //                     method: 'POST',
    //                     headers: {
    //                         'Content-Type': 'application/json; charset=UTF-8'
    //                     }
    //                 };
    //                 console.log("jsonObj")
    //                 console.log(jsonObj.data)
    //                 var queryData = JSON.stringify({
    //                     background: 'https://qiqiutree.leyougame.cc/background0519.png',
    //                     dress: [
    //                         {
    //                             type: 'image',
    //                             url: jsonObj.data, //二维码地址
    //                             xposition: 580,
    //                             yposition: 2030,
    //                             gravity: "NorthWest",
    //                             ws: 0.22
    //                         }
    //                     ]
    //                 });
    //
    //                 let postReq = https.request(postOption, function (postRes) {
    //                     postRes.on('data', function (buffer) {
    //                         let postJson = JSON.parse('' + buffer);
    //                         if (postJson.code == '000') {
    //                             userInfo.poster_list.poster_three = postJson.data;
    //                             //将用户信息赋值回login服务器内存
    //                             self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
    //                             });
    //                             //推送消息给客户端
    //                             next(null, {
    //                                 code: self.consts.Code.SUC,
    //                                 msg: self.consts.Msg.RESULT_SUCCESS,
    //                                 data: postJson.data
    //                             });
    //                             return;
    //                         } else {
    //                             console.log('err: ', postJson.message)
    //                         }
    //                     });
    //                 });
    //                 postReq.on('error', (e) => {
    //                     console.log("err", e)
    //                 });
    //                 postReq.write(queryData);
    //                 postReq.end();
    //             }
    //         });
    //     });
    //     req.on('error', function (e) {
    //         console.log("err ", e)
    //     });
    //     req.end();
    //
    //
    // });
}

/**
 * 获取矿工图谱
 * @param msg
 * @param session
 * @param next
 */
handler.c2sPitManMap = function (msg, session, next) {
    var self = this;
    //推送消息给客户端
    next(null, {
        code: self.consts.Code.SUC,
        msg: self.consts.Msg.RESULT_SUCCESS,
        data: pitman
    });
}

/**
 * 获取用户的离线奖励
 * @param msg
 * @param session
 * @param next
 */
handler.c2sGetOfflineReward = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');
    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        //0级用户不给离线奖励
        if (userInfo.current_level == 0) {
            next(null, {
                code: self.consts.Code.SUC,
                msg: self.consts.Msg.RESULT_SUCCESS,
                data: {
                    coins: 0, //金币数量
                    chest: 0 //宝箱数量
                }
            });
            return;
        }
        //没有上次离线的记录，奖励金币0
        if (!utils.isRealNum(userInfo.last_logout_time)) {
            next(null, {
                code: self.consts.Code.SUC,
                msg: self.consts.Msg.RESULT_SUCCESS,
                data: {
                    coins: 0, //金币数量
                    chest: 0 //宝箱数量
                }
            });
            return;
        }
        var lastLogout = userInfo.last_logout_time / 1000;
        var current = time.currentUnix();
        //离线十分钟以上有离线奖励
        if (current <= lastLogout || (current - lastLogout) < 600) {
            next(null, {
                code: self.consts.Code.SUC,
                msg: self.consts.Msg.RESULT_SUCCESS,
                data: {
                    coins: 0, //金币数量
                    chest: 0 //宝箱数量
                }
            });
            return;
        }
        //离线总时间，查过一天按照一天计算
        var difftime = (current - lastLogout) > 86400 ? 86400 : current - lastLogout;
        //矿层信息
        var levelInfo = userInfo.levelInfo;
        var productSum = 0;
        for (var i = 0; i < levelInfo.length; i++) {
            productSum += parseFloat(levelInfo[i].product);
        }
        //离线奖励金币，为在线的1/10
        var reward = productSum * difftime / 10;
        //判断宝箱数量
        var chestNum = 0;
        if (difftime >= 3600 && difftime < 10800) { //1～3小时 奖励1个宝箱
            chestNum = 10;
        } else if (difftime >= 10800 && difftime < 36000) {  //3~10小时 奖励2个宝箱
            chestNum = 20;
        } else { //超过10小时 奖励3个宝箱
            chestNum = 30;
        }
        //记录待领取的奖励
        userInfo.offline_reward = {
            ticket: utils.genUuid(utils.consts.TYPE_RAND), //领取凭证
            real_coins: reward, //金币数量
            coins: utils.formatCoins(reward), //格式化金币数量
            chest: chestNum //宝箱数量
        }
        //将用户信息赋值回login服务器内存
        self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
        });
        next(null, {
            code: self.consts.Code.SUC,
            msg: self.consts.Msg.RESULT_SUCCESS,
            data: userInfo.offline_reward
        });
        return;
    });
}

/**
 * 开启3分钟双倍产金奖励
 * @param msg
 * @param session
 * @param next
 */
handler.c2sOpenDoubleEarning = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');

    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        userInfo.isDouble = true;
        userInfo.beginDouble = time.currentUnix();
        //看视频次数已满
        if (userInfo.video_num >= consts.Constant.DAILY_VIDEO_TIME) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.VIDEO_NUM_ERR
            });
            return;
        }
        //视频次数增加
        userInfo.video_num = parseInt(userInfo.video_num) + 1;

        //将用户信息赋值回login服务器内存
        self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
        });

        let totalPro = utils.calTotalProduction(userInfo.levelInfo);
        //秒产金量增加消息推送
        self.app.rpc.area.areaRemote.pushMessageToClient(session, uid, session.frontendId, consts.PushRoute.PRODUCT_COINS_CHANGE, {
            product: utils.formatCoins(totalPro * 2),
            offline: utils.formatCoins(totalPro / 10),
            action: 'add',
            type: 'double'
        }, function (err) {
            if (!!err) {
                console.log(err)
            }
        });
        //看视频次数增加消息推送
        self.app.rpc.area.areaRemote.pushMessageToClient(session, uid, session.frontendId, consts.PushRoute.VIDEO_NUM_INCREASE, {
            current: userInfo.video_num,
            increase: 1
        }, function (err) {
            if (!!err) {
                console.log(err)
            }
        });

        next(null, {
            code: self.consts.Code.SUC,
            msg: self.consts.Msg.RESULT_SUCCESS
        });
        return;
    });
}

/**
 * 领取用户的离线奖励
 * @param msg
 * @param session
 * @param next
 */
handler.c2sTakeOfflineReward = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');
    var ticket = msg.ticket; //领奖卷
    var way = msg.way; //领奖方式
    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        //没有离线奖励记录
        if (!userInfo.offline_reward || !userInfo.offline_reward.ticket) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.HAVE_NOT_OFFLINE_REWARD
            });
            return;
        }
        //领奖卷错误
        if (ticket != userInfo.offline_reward.ticket) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.TICKET_WRONG_ERR
            });
            return;
        }
        var increase = userInfo.offline_reward.real_coins;
        if (way == 1) { //普通领奖
            userInfo.coins += userInfo.offline_reward.real_coins;
            userInfo.ordinary_treasure_num = parseInt(userInfo.ordinary_treasure_num) + parseInt(userInfo.offline_reward.chest);
        } else { //视频领奖，双倍奖励
            //看视频次数已满
            if (userInfo.video_num >= consts.Constant.DAILY_VIDEO_TIME) {
                next(null, {
                    code: self.consts.Code.ERR,
                    msg: self.consts.Msg.VIDEO_NUM_ERR
                });
                return;
            }
            //视频次数增加
            userInfo.video_num = parseInt(userInfo.video_num) + 1;
            userInfo.coins += userInfo.offline_reward.real_coins * 2;
            userInfo.superior_treasure_num = parseInt(userInfo.superior_treasure_num) + parseInt(userInfo.offline_reward.chest);
            increase *= 2;
            //看视频次数增加消息推送
            self.app.rpc.area.areaRemote.pushMessageToClient(session, uid, session.frontendId, consts.PushRoute.VIDEO_NUM_INCREASE, {
                current: userInfo.video_num,
                increase: 1
            }, function (err) {
                if (!!err) {
                    console.log(err)
                }
            });
        }
        //清空待领奖信息
        userInfo.offline_reward = {};
        //将用户信息赋值回login服务器内存
        self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
        });
        //金币增加消息推送
        self.app.rpc.area.areaRemote.pushMessageToClient(session, uid, session.frontendId, consts.PushRoute.COINS_INCREASE, {
            increase: utils.formatCoins(increase),
            current: utils.formatCoins(userInfo.coins)
        }, function (err) {
            if (!!err) {
                console.log(err)
            }
        });
        next(null, {
            code: self.consts.Code.SUC,
            msg: self.consts.Msg.RESULT_SUCCESS
        });
        return;
    });
}

/**
 * 用户领取普通宝箱
 * @param msg
 * @param session
 * @param next
 */
handler.c2sTakeChest = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');
    var way = parseInt(msg.way); //领奖类型
    var appear = parseInt(msg.appear); //宝箱出现方式
    var num = parseInt(msg.num); //领取数量
    var ticket = msg.ticket; //宝箱领取的凭证

    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        //如果凭据池不存在，或者凭据不在池中
        if (!userInfo.chest_pool || userInfo.chest_pool.indexOf(ticket) == -1) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.INVALID_CHEST_TICKET
            });
            return;
        } else {
            //从凭证池中删除凭证
            userInfo.chest_pool.splice(userInfo.chest_pool.indexOf(ticket), 1);
            //有冗余的凭证信息，保留最新5条凭证，其余删除
            if (userInfo.chest_pool.length > 5) {
                let arr = userInfo.chest_pool;
                arr.reverse();
                userInfo.chest_pool = arr.slice(0, 5);
            }
        }
        //漂浮式宝箱，判断看视频次数是否已满
        if (appear == 2) {
            //看视频次数已满
            if (userInfo.video_num >= consts.Constant.DAILY_VIDEO_TIME) {
                next(null, {
                    code: self.consts.Code.ERR,
                    msg: self.consts.Msg.VIDEO_NUM_ERR
                });
                return;
            }
            //视频次数增加
            userInfo.video_num = parseInt(userInfo.video_num) + 1;
            //看视频次数增加消息推送
            self.app.rpc.area.areaRemote.pushMessageToClient(session, uid, session.frontendId, consts.PushRoute.VIDEO_NUM_INCREASE, {
                current: userInfo.video_num,
                increase: 1
            }, function (err) {
                if (!!err) {
                    console.log(err)
                }
            });
        }
        var currentTreasure = 0;
        if (way == 1) { //普通宝箱
            userInfo.ordinary_treasure_num += num;
            currentTreasure = userInfo.ordinary_treasure_num;
        } else { //高级宝箱
            userInfo.superior_treasure_num += num;
            currentTreasure = userInfo.superior_treasure_num;
        }
        //将用户信息赋值回login服务器内存
        self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
        });
        //宝箱增加消息推送
        self.app.rpc.area.areaRemote.pushMessageToClient(session, uid, session.frontendId, consts.PushRoute.CHEST_INCREASE, {
            increase: num,
            current: currentTreasure,
            type: way
        }, function (err) {
            if (!!err) {
                console.log(err)
            }
        });
        next(null, {
            code: self.consts.Code.SUC,
            msg: self.consts.Msg.RESULT_SUCCESS
        });
        return;
    });
}

/**
 * 看视频加金币
 * @param msg
 * @param session
 * @param next
 */
handler.c2sMakeMoneyByVideo = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');

    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        //看视频次数已满
        if (userInfo.video_num >= consts.Constant.DAILY_VIDEO_TIME) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.VIDEO_NUM_ERR
            });
            return;
        }
        let increase = 0;

        //15层外4000秒
        if (userInfo.current_level > 15) {
            increase = utils.calTotalProduction(userInfo.levelInfo) * 4000;
        } else { //15层内2000秒
            increase = utils.calTotalProduction(userInfo.levelInfo) * 2000;
        }
        //徒弟助力金币加成
        utils.apprenticeHelpNum(userInfo.uid, function (err, num) {
            //无异常、且助力加层大于0
            if (!err && num > 0) {
                let help = parseFloat((num / 100).toFixed(2));
                increase = increase + increase * help;
            }
            //增加的金币
            userInfo.coins += increase;
            //视频次数增加
            userInfo.video_num = parseInt(userInfo.video_num) + 1;
            //将用户信息赋值回login服务器内存
            self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
            });
            //金币增加消息推送
            self.app.rpc.area.areaRemote.pushMessageToClient(session, uid, session.frontendId, consts.PushRoute.COINS_INCREASE, {
                increase: utils.formatCoins(increase),
                current: utils.formatCoins(userInfo.coins)
            }, function (err) {
                if (!!err) {
                    console.log(err)
                }
            });
            //看视频次数增加消息推送
            self.app.rpc.area.areaRemote.pushMessageToClient(session, uid, session.frontendId, consts.PushRoute.VIDEO_NUM_INCREASE, {
                current: userInfo.video_num,
                increase: 1
            }, function (err) {
                if (!!err) {
                    console.log(err)
                }
            });
            next(null, {
                code: self.consts.Code.SUC,
                msg: self.consts.Msg.RESULT_SUCCESS,
                data: utils.formatCoins(increase)
            });
            return;
        });
    });
}

/**
 * 获取当前看视频能领取多少金币
 * @param msg
 * @param session
 * @param next
 */
handler.c2sHowMuchGetByVideo = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');

    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        let increase = 0;
        //15层外100秒
        if (userInfo.current_level > 15) {
            increase = utils.calTotalProduction(userInfo.levelInfo) * 4000;
        } else { //15层内600秒
            increase = utils.calTotalProduction(userInfo.levelInfo) * 2000;
        }
        next(null, {
            code: self.consts.Code.SUC,
            msg: self.consts.Msg.RESULT_SUCCESS,
            data: utils.formatCoins(increase)
        });
        return;
    });
}

/**
 * 看视频加抽奖次数
 * @param msg
 * @param session
 * @param next
 */
handler.c2sIncreaseLotteryByVideo = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');

    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        //看视频次数已满
        if (userInfo.video_num >= consts.Constant.DAILY_VIDEO_TIME) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.VIDEO_NUM_ERR
            });
            return;
        }
        //抽奖次数增加
        userInfo.luck_draw_num = parseInt(userInfo.luck_draw_num) + consts.Constant.VIDEO_INCREASE_LOTTERY;
        //视频次数增加
        userInfo.video_num = parseInt(userInfo.video_num) + 1;
        //将用户信息赋值回login服务器内存
        self.app.rpc.login.loginRemote.setUser(session, userInfo, function (err, user) {
        });
        //抽奖券变更提醒
        self.app.get('channelService').pushMessageByUids(consts.PushRoute.LOTTERY_TICKET_CHANGE, {
            current: userInfo.luck_draw_num
        }, [{
            uid: uid,
            sid: session.frontendId
        }], null, function (err) {
            if (!!err) {
                logger.error("err: ", err)
            }
        });
        //看视频次数增加消息推送
        self.app.rpc.area.areaRemote.pushMessageToClient(session, uid, session.frontendId, consts.PushRoute.VIDEO_NUM_INCREASE, {
            current: userInfo.video_num,
            increase: 1
        }, function (err) {
            if (!!err) {
                console.log(err)
            }
        });
        next(null, {
            code: self.consts.Code.SUC,
            msg: self.consts.Msg.RESULT_SUCCESS,
            data: {
                current: userInfo.luck_draw_num,
                increase: consts.Constant.VIDEO_INCREASE_LOTTERY
            }
        });
        return;
    });
}

/**
 * 获取活动通知
 * @param msg
 * @param session
 * @param next
 */
handler.c2sGetActiveMessage = function (msg, session, next) {
    var self = this;
    var content = '尊敬的玩家：\n' +
        '「相玉有钱」公测两天时间内，累计在线用户达两万人！！\n' +
        '累计注册用户达十万人！！\n' +
        '为了优化用户体验，如有问题可随时联系客服。微信号：xyyqkf001\n' +
        '2020年5月20日 相玉有钱运营团队';
    var title = '致玩家';
    next(null, {
        code: self.consts.Code.SUC,
        msg: self.consts.Msg.RESULT_SUCCESS,
        data: {
            title: title,
            content: content,
            begin: "2020-05-18",
            end: "2020-05-19"
        }
    });
    return;
}

/**
 * 获取游戏介绍配置
 * @param msg
 * @param session
 * @param next
 */
handler.c2sGetIntroduceMessage = function (msg, session, next) {
    var self = this;
    var message = [];
    next(null, {
        code: self.consts.Code.SUC,
        msg: self.consts.Msg.RESULT_SUCCESS,
        data: message
    });
    return;
}
/**
 * 获取新手奖励消息
 * @param {*} msg 
 * @param {*} session 
 * @param {*} next 
 */
handler.c2sRequestNewPlayerPrize = async function(msg,session,next){
    let uid = session.uid;
    //验证用户登陆
    if(!uid){
        next(null,{
            code:consts.Code.ERR,
            msg:consts.Msg.MISSING_PARAMETER
        })
    }
    let userInfo = await getUserInfo.call(this,session,uid);
    if(userInfo){
        //已经下发过
        if(userInfo.new_player_prize){
            next(null,{
                code:consts.Code.ERR,
                msg:consts.Msg.NEW_PLAYER_PRIZE_GONE
            })
        }else{
            next(null,{
                code:consts.Code.SUC,
                msg:consts.Msg.RESULT_SUCCESS,
                data:{
                    oil:consts.Constant.NEW_PLAYER_OIL,
                    coins:consts.Constant.NEW_PLAYER_COINS
                }
            })
        }
    }else{
        next(null,{
            code:consts.Code.ERR,
            msg:consts.Msg.MISSING_PARAMETER
        })
    }
}

handler.c2sGetNewPlayerPrize = async function(msg,session,next){
    let uid = session.uid;
    //验证用户登陆
    if(!uid){
        next(null,{
            code:consts.Code.ERR,
            msg:consts.Msg.MISSING_PARAMETER
        })
    }
    let userInfo = await getUserInfo.call(this,session,uid);
    if(userInfo){
        if(!userInfo.new_player_prize){//没有领过
            //下发奖励
            try {
                await addUserOil.call(this,session,uid,consts.Constant.NEW_PLAYER_OIL,consts.OIL_ADD_TYPE.NEW_PLAYER_PRIZE);
                await addUserConis.call(this,session,uid,consts.Constant.NEW_PLAYER_COINS,true);
                let _user = await getUserInfo.call(this,session,uid);
                _user.new_player_prize = 1;
                await saveUserInfo.call(this,session,_user);
                next(null,{
                    code:consts.Code.SUC,
                    msg:consts.Msg.RESULT_SUCCESS
                }) 
            } catch (error) {
                next(null,{
                    code:consts.Code.ERR,
                    msg:consts.Msg.DATA_ERR
                })
                throw new Error(error);
            }
            
            
        }else{
            next(null,{
                code:consts.Code.ERR,
                msg:consts.Msg.NEW_PLAYER_PRIZE_GONE
            })
        }
    }else{
        next(null,{
            code:consts.Code.ERR,
            msg:consts.Msg.MISSING_PARAMETER
        })
    }
}
/**
 * 石油交易
 * @param {*} msg {phone:手机号,value:交易数额}
 * @param {*} session 
 * @param {*} next 
 */
handler.c2sMoveOil =  async function(msg,session,next){
    let uid = session.uid;
    let toPhone = msg.phone;
    let giveValue = msg.value;
    let self = this;
    toPhone = parseInt(toPhone);
    giveValue = parseInt(giveValue);
    if(isNaN(toPhone)){
        next(null,{
            code:consts.Code.ERR,
            msg:consts.Msg.GIVE_OIL_ERR1
        })
        return
    }
    if(isNaN(giveValue)){
        next(null,{
            code:consts.Code.ERR,
            msg:consts.Msg.GIVE_OIL_ERR
        })
        return
    }
    //验证用户登陆
    if(!uid){
        next(null,{
            code:consts.Code.ERR,
            msg:consts.Msg.MISSING_PARAMETER
        })
    }
    if(giveValue<consts.Constant.GIVI_OIL_LIMIT){
        next(null,{
            code:consts.Code.ERR,
            msg:consts.Msg.GIVE_OIL_ERR
        })
        return
    }
    //获取交易对象UID
    let toUser;
    try {
        toUser = await getUserByPhone(toPhone);
        if(!toUser){
            next(null,{
                code:consts.Code.ERR,
                msg:consts.Msg.GIVE_OIL_ERR1
            })
            return
        }
    } catch (error) {
        next(null,{
            code:consts.Code.ERR,
            msg:consts.Msg.GIVE_OIL_ERR1
        })
        return
    }
    let userInfo = await getUserInfo.call(self,session,uid);
    if(userInfo){//todu无法判断是否在线
        //税率
        let level = await GetCommanderLevel.call(self,session);
        let fee = consts.Constant.GIVE_OIL_TEX[level-1]||0.2;
        fee = 1+fee;
        if(userInfo.oil<giveValue*fee){
            next(null,{
                code:consts.Code.ERR,
                msg:consts.Msg.GIVE_FAILD_1
            })
            return;
        }
        
        let onLineInfo = await getUserInfo.call(self,session,toUser.uid);
        if(onLineInfo){//在线
            if(uid == onLineInfo.uid){//不能和自己交易
                next(null,{
                    code:consts.Code.ERR,
                    msg:consts.Msg.GIVE_FAILD_SELF
                })
                return;
            }
            try {
                await addUserOil.call(self,session,uid,-giveValue*fee,consts.OIL_ADD_TYPE.GIVE_OIL,JSON.stringify({toUid:onLineInfo.uid}))
            } catch (error) {
                next(null,{
                    code:consts.Code.ERR,
                    msg:consts.Msg.GIVE_FAILD
                })
                return
            }
            // await addUserOil.call(self,session,onLineInfo.uid,giveValue,consts.OIL_ADD_TYPE.GIVE_OIL);
            var connectorServers = self.app.getServersByType('connector');
            let frontendId = dispatch(onLineInfo.uid,connectorServers).id;
            // console.warn("///=====>>>在线交易",uid,onLineInfo.uid,frontendId);
            self.app.rpc.login.loginRemote.addOil(session,onLineInfo.uid,frontendId,giveValue,consts.OIL_ADD_TYPE.GIVE_OIL,JSON.stringify({fromUid:uid}),(err,res)=>{
                if(err){
                    next(null,{
                        code:consts.Code.ERR,
                        msg:consts.Msg.GIVE_FAILD
                    })
                    return
                }else{
                    next(null,{
                        code:consts.Code.SUC,
                        msg:consts.Msg.RESULT_SUCCESS
                    })
                }
            })
            
        }else{//不在线
            // console.warn("///=====>>>离线交易",uid,toUser.uid);
            if(uid == toUser.uid){//不能和自己交易
                next(null,{
                    code:consts.Code.ERR,
                    msg:consts.Msg.GIVE_FAILD_SELF
                })
                return;
            }
            //{money, total_money, oil, total_oil}
            let toUserMoney = await getUserMoneyAndOil.call(self,toUser.uid)
            var connectorServers = self.app.getServersByType('connector');
            let frontendId = dispatch(toUser.uid,connectorServers).id;
            toUser.oil = toUserMoney.oil;
            self.app.rpc.login.loginRemote.updateOffLineOil(session, toUser,frontendId,giveValue, consts.OIL_ADD_TYPE.GIVE_OIL, JSON.stringify({fromUid:uid}),async function (err) {
                if(err){
                    next(null,{
                        code:consts.Code.ERR,
                        msg:consts.Msg.GIVE_FAILD
                    })
                    return
                }else{
                    await addUserOil.call(self,session, uid, -giveValue*fee, consts.OIL_ADD_TYPE.GIVE_OIL,JSON.stringify({toUid:toUser.uid}));
                    next(null,{
                        code:consts.Code.SUC,
                        msg:consts.Msg.RESULT_SUCCESS
                    })
                }
            })
        }
        
    }
}
